/**
 * Created by Administrator on 2018-12-27.
 */
var widgetUtil={
    baseScript:"",
    loadPage:function(form,formSelects,laydate,layedit,element,laytpl,widgetId,classFlag){
        //var url = this.switchPage(classFlag);
        $.getJSON(basePath+"/xdWidget/edit",{id:widgetId,classFlag:classFlag},function(rst){
            if(rst.code !=0){
                layer.msg(rst.msg)
            }
            $("#xdWidget-attr-dom").load(rst.html,function(data){
                widgetUtil.baseScript = rst.baseScript;

                widgetUtil.setAutoFlagDom(rst.table == null ? false : rst.table.autoFlag)

                form.val("xdWidget-attr-form",{classFlag:classFlag})
                form.val("xdWidget-attr-form",rst.data)
                getDataByType(rst.data.dataType,formSelects,rst.data)
                form.val("xdWidget-panel-tb-form",rst.table)


                widgetUtil.initTableCols(rst.cols);

                formSelects.render()
                form.render('checkbox');
                form.render('radio');
                element.render('collapse')
                widgetUtil.initDataSource(form,"#dataSourceId",rst.data.dataSourceId)
                if(rst.data.dataSql || rst.data.dataPanelId){//如果该panel未关联table或echart，则无需刷新
                    getSQLFieldByPanel($("#id").val())
                }

                listPanelParam()

            })
        })
    },
    initTableCols:function(cols){
        var headGrade = []
        var colsArray = []
        var  headDiv = $("#xdWidget-panel-addHead-div")
        headDiv.empty()
        $(cols).each(function(index,item){
            if($.inArray(item.grade, headGrade) < 0){
                headGrade.push(item.grade)
                //➕表头
                laytpl($("#xdWidget-panel-addHead-dom").html()).render(item,function(htmlCode){
                    headDiv.append(htmlCode)
                })
            }
            if($.inArray(item.id, colsArray) < 0){
                colsArray.push(item.id)
                //➕字段
                laytpl($("#xdWidget-panel-col-dom").html()).render(item,function(htmlCode){
                    $("#head-grade-"+item.grade).append(htmlCode)
                })
            }

        })
    },
    createHtml:function(param){
        var nameFlag = param.nameFlag;
        var htmlDom = $(param.baseScript)
        htmlDom.find(".layui-card-header").remove()
        var cardHeader = "<div class='layui-card-header' id='card-header-"+param.label+"'>"+param.name+"</div>"
        if(nameFlag){
            htmlDom.prepend(cardHeader)
        }
        var result = htmlDom.prop("outerHTML")
        return result
    },
    initDataSource:function(form,dom,value){
        $.getJSON(basePath+"/xdDataSource/all",function(rst){
            if(rst.code ==0){
                $(dom).html("<option value=''></option>")
                $.each(rst.data,function(i,item){
                    $(dom).append("<option value='"+item.ID+"'>"+item.SOURCE_NAME+"</option>")
                })
            }
            $(dom).val(value)
            form.render("select")
        })
    },
    setAutoFlagDom:function (value){ //设置自动更新时间戳dom
    if(value == "true"){
        $("#xdWidget-table-autoFlag").after( $("#xdWidget-table-autoInterval-dom").html())
    }else{
        $("#xdWidget-table-autoInterval").remove()
    }
}

}


var laytpl;
layui.config({
    base: basePath+'/layui/lay/modules/'
}).extend({
    formSelects: 'formSelects-v4'
}).use([ 'table','form','formSelects' ,'element','laydate','laytpl','layedit','util','code'], function() {
    var $ = layui.$;
    var form = layui.form;
    var formSelects = layui.formSelects;
    var layer = layui.layer;
    var table = layui.table;
    var element = layui.element;
    var laydate= layui.laydate;
    laytpl = layui.laytpl;
    var layuiutil = layui.util
    var layedit = layui.layedit;
    layui.code();
    var layindex

    $("#widget-add").click(function(){
        layindex = layer.open({
            type:1,
            title:"<i class='layui-icon layui-icon-note'> 新增</i>",
            content: $("#xdWidget-add-dom").html(),
            area: ['30%', '50%'],
            end : function(){
                table.reload("xdWidget-tb")
                $("#xdWidget-attr-dom").empty()
            },
            success:function(layero, index){
                formSelects.data('xdWidgetId', 'server', {
                    url: basePath+'/xdWidget/xdWidgets',
                    data:{panelFlag:true}
                });
            }
        })
    })

    $("#searchStr").bind('input propertychange', function() {
        table.reload("xdWidget-tb")
    });


    form.on("submit(xdWidget-add-form-bt)",function(d){
        //console.log(d)
        var param = d.field;
        $.getJSON(basePath+"/xdWidget/getOne",{id:param.xdWidgetId},function(rst){
            console.log(rst)
            if(rst.code==0){
                var domId = rst.domId
                var html = $(rst.data.html)
                html.attr("id","dom-"+domId).attr("lay-filter","dom-"+domId)
                html = html.prop("outerHTML")
                param.domId = domId
                param.html = html

                laytpl($("#panel-html-dom").html()).render(param,function(htmlCode){
                    param.html = htmlCode
                    $.getJSON(basePath+"/xdWidget/addXdWidget",param,function(data){
                        if(data.code==0){
                            table.reload("xdWidget-tb")
                            layer.close(layindex);
                        }else{
                            layer.msg(data.msg)
                        }
                    })
                })
            }
        })

        return false;
    })


    var tableOption = {
        elem: '#xdWidget-tb'
        ,url: basePath + '/xdWidget/listXdWidgetPanel'
        ,where:{searchStr:function(){return $("input[name='searchStr']").val()}}
        ,method:"post"
        ,toolbar:false
        ,title:"系统参数配置"
        ,defaultToolbar:false//['filter', 'print']
        ,cols: [[
            {title:"选择",fixed:'left', width:60,templet:function(d){
                return '<input type="radio" name="tb-radio" lay-filter="tb-radio"  value="'+d.ID+'" class-flag="'+ d.CLASS_FLAG+'" >'
            }},
            {field:'NAME', title: '标题',fixed:'left',sort:true,templet:function(d){
                return  d.NAME
            }}
            //,{field:'LABEL', title: '标签',sort:true}
            ,{field:'XD_WIDGET', title: 'Widget',sort:true }
            //,{field:'CREATOR', title: 'CREATOR',sort:true }
            ,{title: "操作", width:60,fixed:'right',templet:function(d){
                return '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delWidget">删除</a>'
            }}
        ]]
        ,page: {groups:3,layout:['prev', 'page', 'next','refresh']}
        ,height: 'full-80'
    }


    var tableDom = table.render(tableOption)

    table.on("tool(xdWidget-tb)",function(obj) {
        var data = obj.data
        if(obj.event === 'delWidget'){//删除行
            var param = {classFlag:data.CLASS_FLAG,id:data.ID};
            layer.confirm("确定要删除该记录吗，此操作不能恢复!", {icon: 3, title:'提示'}, function (index) {
                    $.ajax(basePath+"/xdWidget/del",{
                        dataType:"json",
                        type:"post",
                        data:param,
                        success:function(rdata){
                            layer.msg(rdata.msg)
                            if(rdata.code == 0){
                                table.reload("xdWidget-tb")
                            }
                            $("#xdWidget-attr-dom").empty()
                        }
                    });
                    layer.close(index);
                }
            )
        }
    })

    form.on('radio(tb-radio)', function(data){
        //console.log( data.elem ); //得到radio原始DOM对象
        //被点击的radio的value值
        //console.log(data.value,$(data.elem).attr("class-flag"));
        var id = data.value;
        var classFlag = $(data.elem).attr("class-flag")
        var divHeight = $('.xd-div-sample').height()
        var h1 = $('.xd-div-sample2').height()
        //console.log(divHeight,divHeight-43)
        $("#xdWidget-attr-dom").css("height",divHeight-h1-3)

        if(classFlag === "xd-panel-table"){
            widgetUtil.loadPage(form,formSelects,laydate,layedit,element,laytpl,id,classFlag)
        }


    });


    //更新classFlag对应widget
    form.on("submit(xdWidget-panel-form-bt)",function(obj){
        var param = obj.field
        //console.log(param)
        param.baseScript = widgetUtil.baseScript
        param.html = widgetUtil.createHtml(param)
        //console.log(param)
        $.post(basePath+"/xdWidget/save",param,function(rst){
            layer.msg(rst.msg)
        },"json")
        return false;
    })

    form.on("submit(xdWidget-panel-tb-form-bt)",function(obj){
        var param = obj.field
        param.widgetPanelId = $("#id").val()

        $.post(basePath+"/xdTableCfg/save",param,function(rst){
            if(rst.code !=0){
                layer.alert(rst.msg)
            }else{
                $("#dataId").val(rst.data.dataId)
                layer.msg(rst.msg)
            }
        },"json")
        return false
    })


    form.on("submit(xdWidget-panel-form-view-bt)",function(obj){
        var param = obj.field
        //console.log(param)

        layer.open({
            type:1,
            title:"<i class='layui-icon layui-icon-note'></i>&nbsp;数据预览",
            content:$("#panel-view-tb-dom").html(),
            area: ['95%', '98%'],
            maxmin:true,
            success:function(){
                var indexLoad = layer.load();
                $.post(basePath+"/xdWidgetPanel/viewPanelData",param,function(rst){
                    if(rst.code !=0){
                        layer.alert(rst.msg)
                    }else{
                        var tableOption = {
                            elem: '#panel-view-tb'
                            ,data: rst.data
                            ,method:"post"
                            ,toolbar:false
                            ,defaultToolbar:false//['filter', 'print']
                            ,cols:rst.cols
                            ,page: true
                            ,height: 'full-100'

                        }
                        table.render(tableOption)
                    }
                    layer.close(indexLoad)
                },"json")
            }
        })

        return false;
    })

    form.on("submit(xdWidget-panel-sql-view-bt)",function(obj){
        var param = obj.field
        //console.log(param)

        layer.open({
            type:1,
            title:"<i class='layui-icon layui-icon-note'></i>&nbsp;SQL预览",
            content:$("#panel-view-sql-dom").html(),
            area: ['95%', '98%'],
            maxmin:true,
            success:function(){
                var indexLoad = layer.load();
                $.post(basePath+"/xdWidgetPanel/viewPanelSql",param,function(rst){
                    if(rst.code !=0){
                        layer.alert(rst.msg)
                    }else{
                       $("#panel-view-sql").html(rst.data)
                    }
                    layer.close(indexLoad)
                },"json")
            }
        })

        return false;
    })

    //数据集
    form.on('radio(dataType)', function(data){
        var value = data.value
        getDataByType(value,formSelects,{})
    });

    //获取字段
    form.on("submit(xdWidget-panel-sqlField)",function(obj){
        getSQLFieldByPanel($("#id").val())
    })

    //添加表头 addHeader
    form.on("submit(xdWidget-panel-addHead-bt)",function(obj){
        var headDiv = $("#xdWidget-panel-addHead-div")
        var param = {grade:headDiv.find(".panel-addHead-dom").size()+1}
        laytpl($("#xdWidget-panel-addHead-dom").html()).render(param,function(htmlCode){
            headDiv.append(htmlCode)
        })
    })
    //添加字段 addField
    form.on("submit(panel-addField-bt)",function(obj){
        var elem = obj.elem;
        var xdTableId = $("#dataId").val()
        var grade = $(elem).attr("head-grade")

        //新增字段
        var params = {xdTableId:xdTableId,grade:grade}
        panelTableAddField(params,"#head-grade-"+grade );

        return false;
    })
    //字段排序 + 1
    form.on("submit(panel-updateField)",function(obj){
        var elem = $(obj.elem)
        var colId = elem.parent().attr("id")
        var reduce = elem.attr("reduce")//前后移动个数
        var grade = elem.parent().attr("grade")
        var index =  elem.parent().attr("index")
        $.post(basePath+"/xdTableColCfg/setIndex",{id:colId,reduce:reduce},function(rst){
            if(rst.code !=0 && rst.code != 304){
                layer.alert(rst.msg)
            }else{
                var oldColDom = elem.parent()
                if(reduce == -1 ){
                    oldColDom.insertBefore(elem.parent().prev())
                    oldColDom.css({"margin-left":"2px","margin-right":"2px" })
                }else if(reduce == 1){
                    oldColDom.insertAfter(elem.parent().next())
                    oldColDom.css({"margin-left":"2px","margin-right":"2px" })
                }else if(reduce == 0){
                    //oldColDom.remove()
                    widgetUtil.initTableCols(rst.data)
                }
            }
        },"json")
        return false;
    })

    //字段编辑
    form.on("submit(panel-tb-field-edit)",function(obj){
        var elem = $(obj.elem)
        var colId = elem.parent().attr("id")
        commonUtil.openPage("列属性","./xdTableCol.html?id="+colId,"60%","90%")
        return false;
    })

    //预览最终效果
    form.on("submit(xdWidget-previewPanelTable-form-bt)",function(obj){
        var panelId = $("#id").val()
        //commonUtil.openPage("预览","./viewPanelTableLast.html?id="+panelId,"90%","90%")
        window.open("./viewPanelTableLast.html?id="+panelId,"预览")
        return false;
    })

    //删除、排序 pannel绑定参数
    form.on("submit(panel-param-update)",function(obj){
        var elem = $(obj.elem)
        var id = elem.parent().attr("id")
        var flag = elem.attr("flag")//前后移动个数
        $.getJSON(basePath+"/xdWidgetPanel/cfgPanelParam",{id:id,flag:flag},function(rst){
            if(rst.code == 0 && flag=="del"){
                listPanelParam()
            }else if(rst.code==0 && flag==-1){
                var oldColDom = elem.parent()
                oldColDom.insertBefore(elem.parent().prev())
                oldColDom.css({"margin-left":"2px","margin-right":"2px" })
            }
        })
    })

    //table自动刷新
    form.on("select(autoFlag)",function(obj){
        var value = obj.value
        widgetUtil.setAutoFlagDom(value)
    })
});

function getSQLFieldByPanel(panelId){//获取sql-字段
    $.post(basePath+"/xdWidgetPanel/viewSQLFieldByPanel",{id:panelId},function(rst){
        if(rst.code !=0){
            layer.alert(rst.msg)
        }else{
            var fieldHtml = ""
            $.each(rst.data,function(index,item){
                fieldHtml +='<span  draggable="true" ondragstart="drag(event)" class="layui-badge layui-bg-cyan xd-col">'+item.columnName+'</span>&nbsp;'
            })
            $(".panel-sql-field").html(fieldHtml)
            $(".xd-col").click(function(){
                commonUtil.copyToClipBoard('.xd-col',$(this).text())
                $(this).toggleClass("layui-bg-cyan")
            })
        }
    },"json")
}

function getDataByType(value,formSelects,param){
    var  dom = $(".xdWidget-attr-row2")
    $(".dataPanelId").remove()
    $(".dataSql").remove()
    if(value =="SQL"){
        dom.append($("#xdWidget-attr-form-sql").html())
        $("#dataSql").text(param.dataSql)
    }else if(value == "Panel"){
        var id = $("#id").val()
        dom.append($("#xdWidget-attr-form-panel").html())
        formSelects.data("dataPanelId", 'server', {//远程根据 keyword 查询
            type:"post",
            data:{id:id},
            searchUrl:basePath+"/xdWidgetPanel/getPanelExceptSelf",
            success: function(id, url, searchVal, result){           //使用远程方式的error回调
                formSelects.value("dataPanelId",[param.dataPanelId])
            }
        });
    }
}

function editTextarea(dom){
    var url = "editTextArea.html?|"+dom;
    commonUtil.openPage("数据集Sql",url,"60%","70%",false)
}

function viewParam(){
    var panelId=$("#id").val()
    var url = "viewParam.html?panelId="+panelId;
    //commonUtil.openPage("参数绑定",url,"40%","80%",false)
    layer.open({
        type: 2,
        area: ["40%" , "80%" ],
        fix: false, //不固定
        maxmin: true,
        shadeClose: true,
        shade:0.4,
        scrollbar:  false,
        title: "<i class='layui-icon layui-icon-note'></i>&nbsp;参数绑定",
        content: url,
        end: function (index, layero) {
            listPanelParam()
        }
    });
}

//列出panel绑定的参数
function listPanelParam(){
    var panelId=$("#id").val()
    $.getJSON(basePath+"/xdWidgetPanel/listPanelParam",{panelId:panelId},function(rst){
        $("#xdWidget-panel-param-div").empty()
        if(rst.code == 0 ){
            $.each(rst.data,function(index,item){
                $("#xdWidget-panel-param-div").append('<span class="layui-badge-rim" id="'+item.ID+'" >' +
                    '<span class="layui-badge layui-bg-gray" lay-submit lay-filter="panel-param-update" flag="-1"><</span>'+
                    '<span class="layui-badge layui-bg-cyan">'+item.XD_WIDGET+'('+item.NAME+')</span>' +
                    '<span class="layui-badge layui-bg-gray" lay-submit lay-filter="panel-param-update" flag="del">×</span></span>')
                $(".layui-badge-rim").css({"margin-left":"3px","margin-right":"3px" })
            })
        }else{
            layer.msg(rst.msg)
        }
    })
}

function drag(ev)
{
    ev.dataTransfer.setData("Html",$(ev.target).prop("outerHTML"));
}

function allowDrop(event){
    event.preventDefault()
}

function drop(ev)
{
    ev.preventDefault();
    var data= $(ev.dataTransfer.getData("Html"));
    var field = data.html()
    var grade = $(ev.target).attr("grade")
    var xdTableId = $("#dataId").val()
    var params = {field:field,grade:grade,xdTableId:xdTableId}
    panelTableAddField(params,"#head-grade-"+grade)
}

function panelTableAddField(params,targetDom){

    $.post(basePath+"/xdTableColCfg/add",params,function(rst){
        if(rst.code !=0 ){
            if(rst.code == 303){
                layer.alert("请先配置Table属性",{icon: 7},function(index){
                    $(".layui-colla-content").removeClass("layui-show")
                    $("#xdWidget-panel-tb-colla").toggleClass("layui-show")
                    layer.close(index);
                })
            }else{
                layer.alert(rst.msg)
            }
            return
        }else{
            laytpl($("#xdWidget-panel-col-dom").html()).render(rst.data,function(htmlCode){
                $(targetDom).append(htmlCode)
                $(".layui-badge-rim").css({"margin-left":"3px","margin-right":"3px" })
            })
        }
    },"json")
}
